package com.ship.dispatch.service.fob.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.core.utils.DateUtil;
import com.ship.common.core.utils.HttpRequestUtil;
import com.ship.dispatch.bean.SpArrangeSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bo.shipBusiness.ThirdPartyMeasureBo;
import com.ship.dispatch.bo.shipBusiness.ThirdPartyMeasureRecordBo;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.fob.SpFobReturnSalesJlbgMapper;
import com.ship.dispatch.mapper.fob.SpFobReturnSalesZzwjMapper;
import com.ship.dispatch.service.SpArrangeSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobReturnSalesJlbgService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import com.ship.dispatch.service.shipBusiness.SmThirdPartyMeasureService;
import com.ship.dispatch.util.PropertiesUtil;
import com.ship.dispatch.util.StringUtils;
import com.ship.dispatch.vo.shipReport.SynchronThirdPartyMeasureVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobReturnSalesJlbgServiceImpl
 * @description
 * @create 2024/1/6 0006
 */
@Service
public class SpFobReturnSalesJlbgServiceImpl extends FobBaseServiceImpl<SpFobReturnSalesJlbgMapper,SpFobReturnSalesJlbg> implements SpFobReturnSalesJlbgService {

    @Autowired(required = false)
    SpFobReturnSalesJlbgMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;
    @Autowired
    SpArrangeSchemeDetailService spArrangeSchemeDetailService;

    private final AsyncService asyncService;

    public SpFobReturnSalesJlbgServiceImpl(AsyncService asyncService) {
        this.asyncService = asyncService;
    }
    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobReturnSalesJlbg object = JsonUtils.jsonToObject(json,SpFobReturnSalesJlbg.class);
        SpFobReturnSalesJlbg his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesJlbg>().eq(SpFobReturnSalesJlbg::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobReturnSalesJlbg::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            //填充计量信息值
            if((his.getJlReport()==null && object.getJlReport()!=null) || (his.getJlReport()!=null && object.getJlReport()!=null && !his.getJlReport().equals(object.getJlReport()))){
                object.setField3("-1");
                asyncService.executReturnSalesJlbg(his.getId(),object.getJlReport());
                /*SpFobReturnSalesJlbg reportObject = null;
                try {
                    reportObject = relaxJLReport(object.getJlReport());
                } catch (IOException e) {
                    log.error("解析异常",e);
                }
                if(reportObject!=null){
                    try {
                        PropertiesUtil.copyProperties(reportObject,object);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }*/
            }
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesJlbg>().eq(SpFobReturnSalesJlbg::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobReturnSalesJlbg::getStatus,-2));

            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                List<String> tempIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(tempIds);
                // spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
            }
            if((his.getJlReport()!=null && his.getJlReport().length()>0)){
                String temp = his.getJlReport();
                String[] fieldIds = temp.split(",");
                List<String> tempIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(tempIds);
                //
            }
            if((his.getPortLog()!=null && his.getPortLog().length()>0)){
                String temp = his.getPortLog();
                String[] fieldIds = temp.split(",");
                List<String> tempIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(tempIds);
                //
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Resource
    HttpRequestUtil httpRequestUtil;
    public SpFobReturnSalesJlbg relaxJLReport(String fileId) throws Exception {
        SpFobFileRecord fileRecord = spFobFileRecordService.getById(fileId);
        if(fileRecord!=null){
            URL url = new URL(fileRecord.getPath());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            InputStream in = connection.getInputStream();
            if(in!=null){
                JSONObject infos = httpRequestUtil.ocrJLReport(in,fileId);
                SpFobReturnSalesJlbg spFobSyzlzzwj = JsonUtils.jsonToObject(JsonUtils.objectToJson(infos),SpFobReturnSalesJlbg.class);
                return spFobSyzlzzwj;
            }
        }
        return  null;
    }

    public static MultipartFile convert(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        InputStream in = connection.getInputStream();

        byte[] body = new byte[in.available()];
        in.read(body);

        MultipartFile multipartFile = new MockMultipartFile("file", "file", "text/plain", body);

        return multipartFile;
    }
    @Resource
    SmThirdPartyMeasureService smThirdPartyMeasureService;
    // 完成任务执行同步信息
    public void createPayOrder(Long id){
        SpFobReturnSalesJlbg spFobSyzlzzwj = this.getById(id);
        //执行同步逻辑
        Long thirdParty = syncThirdParty(spFobSyzlzzwj);
        spFobSyzlzzwj.setThirdPartyId(thirdParty);
        this.updateById(spFobSyzlzzwj);
    }

    public Long syncThirdParty(SpFobReturnSalesJlbg spFobSyzlzzwj){
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobSyzlzzwj.getProceeInstanceId());
        ThirdPartyMeasureBo thirdPartyMeasureBo = new ThirdPartyMeasureBo();
        thirdPartyMeasureBo.setLoadingStartDate(spFobSyzlzzwj.getLoadingStartDate());
        thirdPartyMeasureBo.setLoadingEndDate(spFobSyzlzzwj.getLoadingEndDate());
        thirdPartyMeasureBo.setVoyageType(5);
        if(execute!=null){
            thirdPartyMeasureBo.setVoyage(execute.getVoyageNo());
            thirdPartyMeasureBo.setLoadingPort(execute.getExpectedLoadingPort());
        }
        //Gross Quantity
        thirdPartyMeasureBo.setLoadingGrossMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGrossQuantityMmbtu()));
        thirdPartyMeasureBo.setLoadingGrossTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGrossQuantityM3()));
        thirdPartyMeasureBo.setLoadingGrossMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGrossQuantityMt()));

        thirdPartyMeasureBo.setLoadingNetMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getNetQuantityMmbtu()));
        thirdPartyMeasureBo.setLoadingNetTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getNetQuantityM3()));
        thirdPartyMeasureBo.setLoadingNetMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getNetQuantityMt()));

        thirdPartyMeasureBo.setLoadingGhv(getStringToBigDecimal(spFobSyzlzzwj.getGhv()));
        thirdPartyMeasureBo.setLoadingTemperature(getStringToBigDecimal(spFobSyzlzzwj.getTemperature()));
        thirdPartyMeasureBo.setLoadingDensity(getStringToBigDecimal(spFobSyzlzzwj.getDensity()));
        thirdPartyMeasureBo.setLoadingGas(getStringToBigDecimal(spFobSyzlzzwj.getGasificationRate()));

        thirdPartyMeasureBo.setLoadingCoolMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getCoolDownMmbtu()));
        thirdPartyMeasureBo.setLoadingCoolTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getCoolDownM3()));
        thirdPartyMeasureBo.setLoadingCoolMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getCoolDownMt()));

        thirdPartyMeasureBo.setLoadingVapourMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getVapourMmbtu()));
        thirdPartyMeasureBo.setLoadingVapourMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getVapourMt()));
        thirdPartyMeasureBo.setLoadingVapourTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getVapourM3()));

        thirdPartyMeasureBo.setLoadingConsumedMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getBogConsumedMmbtu()));
        thirdPartyMeasureBo.setLoadingConsumedMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getBogConsumedMt()));
        thirdPartyMeasureBo.setLoadingConsumedTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getBogConsumedM3()));

        thirdPartyMeasureBo.setLoadingGassingMmbtuQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGassingUpMmbtu()));
        thirdPartyMeasureBo.setLoadingGassingMetersQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGassingUpMt()));
        thirdPartyMeasureBo.setLoadingGassingTonsQuantity(getStringToBigDecimal(spFobSyzlzzwj.getGassingUpM3()));

        if(spFobSyzlzzwj.getComponent()!=null && spFobSyzlzzwj.getComponent()!=""){
            try {
                //解析json数组
                List<JSONObject> list = JsonUtils.jsonToList(spFobSyzlzzwj.getComponent(),JSONObject.class);
                for(int i=0;i<list.size();i++){
                    JSONObject object = new JSONObject(list.get(i));
                    String name = object.getString("name");
                    String value = object.getString("value");
                    if(name.contains("Methane")){
                        thirdPartyMeasureBo.setLoadingMethane(getStringToBigDecimal(value));
                    }else if(name.contains("Ethane")){
                        thirdPartyMeasureBo.setLoadingEthane(getStringToBigDecimal(value));
                    }else if(name.contains("Propane")){
                        thirdPartyMeasureBo.setLoadingPropane(getStringToBigDecimal(value));
                    } else if (name.contains("lso Butane")) {
                        thirdPartyMeasureBo.setLoadingIbutane(getStringToBigDecimal(value));
                    } else if (name.contains("N-Butane")) {
                        thirdPartyMeasureBo.setLoadingNbutane(getStringToBigDecimal(value));
                    } else if (name.contains("lso Pentane")) {
                        thirdPartyMeasureBo.setLoadingIpentane(getStringToBigDecimal(value));
                    } else if (name.contains("N-Pentane")) {
                        thirdPartyMeasureBo.setLoadingNpentane(getStringToBigDecimal(value));
                    }else if (name.contains("N-Hexane")){
                        thirdPartyMeasureBo.setLoadingNhexane(getStringToBigDecimal(value));
                    }else if(name.contains("Nitrogen")){
                        thirdPartyMeasureBo.setLoadingNitrogen(getStringToBigDecimal(value));
                    } else if (name.contains("Oxygen")) {
                        thirdPartyMeasureBo.setLoadingOxygen(getStringToBigDecimal(value));
                    }else if (name.contains("Carbon Dioxide")){
                        thirdPartyMeasureBo.setLoadingDioxide(getStringToBigDecimal(value));
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        SynchronThirdPartyMeasureVo vo = smThirdPartyMeasureService.saveSmThirdPartyMeasure(thirdPartyMeasureBo);
        if(spFobSyzlzzwj.getEvent()!=null && spFobSyzlzzwj.getEvent()!=""){
            try {
                List<JSONObject> list = JsonUtils.jsonToList(spFobSyzlzzwj.getEvent(),JSONObject.class);
                for(int i=0;i<list.size();i++){
                    JSONObject object = new JSONObject(list.get(i));
                    ThirdPartyMeasureRecordBo thirdPartyMeasureRecordBo = new ThirdPartyMeasureRecordBo();
                    thirdPartyMeasureRecordBo.setRecordContent(object.getString("event"));
                    if(object.get("date")!=null && object.getString("event")!=null){
                        thirdPartyMeasureRecordBo.setRecordTime(object.getString("date"));
                        thirdPartyMeasureRecordBo.setRecordType(1);
                        thirdPartyMeasureRecordBo.setThirdPartyMeasureId(vo.getId());
                        smThirdPartyMeasureService.saveSmThirdPartyMeasureRecord(thirdPartyMeasureRecordBo);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        //新增明细
        return vo.getId();
    }

    public BigDecimal getStringToBigDecimal(String num){
        if(StringUtils.isNotEmpty(num)){
            return new BigDecimal(num);
        }
        return null;
    }


    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesJlbg>().eq(SpFobReturnSalesJlbg::getProceeInstanceId,id).ne(SpFobReturnSalesJlbg::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobReturnSalesJlbg spFob = new SpFobReturnSalesJlbg();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobReturnSalesJlbg spFob = new SpFobReturnSalesJlbg();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobReturnSalesJlbg spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesJlbg>().eq(SpFobReturnSalesJlbg::getProceeInstanceId,id).ne(SpFobReturnSalesJlbg::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getJlReport()!=null){
            String[] ids = spFobZzgcjr.getJlReport().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("jlReport",spFobFileRecordList);
        }
        if(spFobZzgcjr.getPortLog()!=null){
            String[] ids = spFobZzgcjr.getPortLog().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("portLog",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        return map;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobReturnSalesJlbg> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobReturnSalesJlbg>().eq(SpFobReturnSalesJlbg::getProceeInstanceId,processInstanceId).orderByDesc(SpFobReturnSalesJlbg::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

}
